package com.jidong.test_springboot.web;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jidong.test_springboot.dao.UserDao;
import com.jidong.test_springboot.entity.User;
import com.jidong.test_springboot.vo.ResultData;
@Controller
@RequestMapping("test/")
public class TestJwtUserServlet{

	@Autowired
	private UserDao dao;

	@RequestMapping("login.do")
	@ResponseBody
	public ResultData login(String username,String password) {
		User u=dao.selectOne(new QueryWrapper<User>().eq("uname", username).eq("pwd", password));
		
		if(u==null) {
			ResultData result=new ResultData();
			result.setCode(200);
			result.setMsg("登录失败");
			return result;
		}
		
		//登录成功，创建jwt
		Builder builder=JWT.create();
		builder.withClaim("username", username);//给jwt携带用户信息
		Date date=new Date(System.currentTimeMillis()+1000*15);
		builder.withExpiresAt(date);//jwt过期时间
		Algorithm algorithm=Algorithm.HMAC256(password);//给任意一个字符串生成一个加密串作为签名 我们这里用密码
		String token=builder.sign(algorithm);//生成秘钥
		
		ResultData result=new ResultData();
		result.setCode(200);
		result.setMsg("登录成功");
		result.setResult("{token:"+token+"}");//把token给前端，前端下次登录的携带该token
		return result;
	}


	@RequestMapping("list.do")
	@ResponseBody
	public ResultData list(String token)  {
		if(token==null) {
			return new ResultData().setCode(401).setMsg("没有登录，请先登录");
		}//没有登录提示的
		//解析token
		DecodedJWT jwt=JWT.decode(token);
		Date date=jwt.getExpiresAt();
		long time=date.getTime()-System.currentTimeMillis();
		if(time<0) {
			return new ResultData().setCode(401).setMsg("token过期，请重新登录");
		}//验证是否过期
		
		String username=jwt.getClaim("username").asString();
		User u=dao.selectOne(new QueryWrapper<User>().eq("uname", username));
		if(u==null) {
			return new ResultData().setCode(401).setMsg("token无效，请登录");
		}//验证携带数据是否有效
		
		Algorithm algorithm=Algorithm.HMAC256(u.getPwd());
		
		//根据用户名和密码生成的签名再重新生成一次token
		JWTVerifier jwtVer=JWT.require(algorithm).withClaim("username", username).build();
		try {
			jwtVer.verify(token);//jwtVer里有个重新生成的token，拿着这个和传来的token进行比较
			//如果正常则不返回任何东西，如果不一样，则抛出异常
		} catch (JWTVerificationException e) {
			return new ResultData().setCode(401).setMsg("token非法，请登录");// 如果密码或者加密方式错误就会提示
		}
		
		
		List<User> users = dao.selectList(null);
		return new ResultData().setCode(200).setResult(users);
	}

}
